package com.tjl.jdbc;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils
{
 private static String driver;
 private static String url;
 private static String username;
 private static String password;

    //使用流的形式获取db.properties中的信息
    //.getClassLoader()用于查找db.properties
    //JDBCUtils.类字节码对象，getClassLoader()为类加载器，详见反射相关内容
    //getResourceAsStream("db.properties")加载properties文件到输入流
    static
    {
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");

        Properties properties = new Properties();
        //加载流文件
        try{
            properties.load(is);
            driver = properties.getProperty("driver");
            //加载MySQLq驱动
            Class.forName(driver);
            System.out.println("驱动加载成功");
            //获得url,username,password
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //获得数据库连接对象的方法
    public static Connection getConnection()
    {
        try {
            System.out.println("数据库连接成功");
            return DriverManager.getConnection(url, username, password);
        }catch (SQLException e){
            System.out.println("数据库连接失败");
            e.printStackTrace();
            return null;
        }
    }

    public static void close( Connection conn ,Statement statement , ResultSet result)
    {
        try {
            if (statement != null)
            {
                statement.close();
                statement = null;
            }
            if (conn != null)
            {
                conn.close();
                conn = null;
            }
            if (result != null)
            {
                result.close();
                result = null;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }


}
